package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"hft/tools/weixin"
	"hft/tools/weixin/model"
	"net/url"

	"hft/e"

	"github.com/tidwall/gjson"
)

// 获取素材列表
type SuCai struct{}

// suCaiType 素材类型 offset页码 count页数
func (*SuCai) List(suCaiType string, offset int, count int) (result *model.SuCaiRes, err error) {
	var data = []byte(fmt.Sprintf(`{"type":"%v","offset":%v,"count":%v}`, suCaiType, offset, count))
	res := weixin.WeiXinBase.BaseRequestV2("POST", "/cgi-bin/material/batchget_material", &url.Values{}, data)
	code := gjson.Get(string(res), "errcode").Int()
	if code != 0 {
		return nil, errors.New(e.InValidMediaID)
	}

	var resList *model.SuCaiRes
	json.Unmarshal(res, &resList)
	return resList, nil
}

func (*SuCai) Count() (count *model.SuCaiCount, err error) {

	res := weixin.WeiXinBase.BaseRequestV2("GET", "/cgi-bin/material/get_materialcount", &url.Values{}, []byte{})

	code := gjson.Get(string(res), "errcode").Int()

	if code != 0 {
		return nil, errors.New(e.ErrorInfo)
	}

	var nowCount *model.SuCaiCount
	json.Unmarshal(res, &nowCount)

	return nowCount, nil

}

func (*SuCai) DraftList(NoContent int, offset int, count int) (result *model.SuCaiRes, err error) {
	var data = []byte(fmt.Sprintf(`{"no_content":"%v","offset":%v,"count":%v}`, NoContent, offset, count))
	res := weixin.WeiXinBase.BaseRequestV2("POST", "/cgi-bin/draft/batchget", &url.Values{}, data)
	code := gjson.Get(string(res), "errcode").Int()
	if code != 0 {
		return nil, errors.New(e.InValidMediaID)
	}

	var resList *model.SuCaiRes
	json.Unmarshal(res, &resList)
	return resList, nil
}

func (*SuCai) DraftCount() (count *model.DraftCount, err error) {

	res := weixin.WeiXinBase.BaseRequestV2("GET", "/cgi-bin/draft/count", &url.Values{}, []byte{})

	code := gjson.Get(string(res), "errcode").Int()

	if code != 0 {
		return nil, errors.New(e.ErrorInfo)
	}

	var nowCount *model.DraftCount
	json.Unmarshal(res, &nowCount)

	return nowCount, nil

}

// 获取永久素材
func (*SuCai) GetForEver(media_id string, materialType string) (resData interface{}, err error) {
	var data = []byte(fmt.Sprintf(`{"media_id":"%v"}`, media_id))
	res := weixin.WeiXinBase.BaseRequestV2("POST", "/cgi-bin/material/get_material", &url.Values{}, data)
	fmt.Println("永久素材", string(res))
	code := gjson.Get(string(res), "errcode").Int()

	if code != 0 {
		return nil, errors.New(e.ErrorInfo)
	}
	var newData *interface{}
	json.Unmarshal(res, &newData)

	return newData, nil

}

var WeiXinSuCai = new(SuCai)
